# coding: utf-8

from flask import Blueprint, render_template, redirect, url_for, flash
from flask_login import login_user, logout_user, login_required, current_user
from flask_principal import Permission, RoleNeed
from flask_login import LoginManager
from datetime import datetime
from dateutil.relativedelta import relativedelta
from borrow_book.forms import BorrowForm, ReturnForm, PayForm
from db.models import db, User, Book, BorrowCard, BorrowBook
from permission_control import permission_required
from const import PERMISSION, BorrowCardApplyStatus
from log import logger
from config import app

borrow_blueprint = Blueprint('user_borrow', __name__)


# 书籍列表
@borrow_blueprint.route('/user_borrow/book/list', methods=['GET'])
@login_required
@permission_required(PERMISSION.PERM_BOOK_VIEW.KEY)
def book_list():
    books = Book.query.filter_by(is_delete=0, is_active=1).all()
    borrow_card = BorrowCard.query.filter_by(user_id=current_user.id).first()
    return render_template('user_borrow/book_list.html', books=books, borrow_card=borrow_card)

# 借阅列表
@borrow_blueprint.route('/user_borrow/borrow/list', methods=['GET'])
@login_required
@permission_required(PERMISSION.PERM_BOOK_VIEW.KEY)
def borrow_list():
    borrow_books = BorrowBook.query.filter_by(user_id=current_user.id, is_return=0).all()
    borrow_card = BorrowCard.query.filter_by(user_id=current_user.id).first()
    return render_template('user_borrow/borrow_list.html', borrow_books=borrow_books, borrow_card=borrow_card)

# 书籍借阅详情展示
@borrow_blueprint.route('/user_borrow/book/<int:book_id>', methods=['GET', 'POST'])
@login_required
@permission_required(PERMISSION.PERM_BORROW.KEY)
def borrow_info(book_id):
    borrow_form = BorrowForm()
    return_form = ReturnForm()
    pay_form = PayForm()
    book = Book.query.filter_by(id=book_id, is_delete=0, is_active=1).first()
    if not book:
        flash('没有找到要借阅的书籍。', 'danger')
        return redirect(url_for('user_borrow.book_list'))
    borrow_book = BorrowBook.query.filter_by(book_id=book_id, user_id=current_user.id, is_return=0).first()
    logger.info(f"当前借阅书籍信息为：{borrow_book}")
    return render_template('user_borrow/borrow_info.html',
                           book=book, 
                           borrow_book=borrow_book,
                           borrow_form=borrow_form, 
                           return_form=return_form,
                           pay_form=pay_form,
                           )


# 借书逻辑
@borrow_blueprint.route('/user_borrow/post_borrow', methods=['POST'])
@login_required
@permission_required(PERMISSION.PERM_BORROW.KEY)
def post_borrow():
    form = BorrowForm()
    if form.validate_on_submit():
        book_id = form.book_id.data
        book = Book.query.filter_by(id=book_id, is_delete=0, is_active=1).first()
        # 校验借书证
        borrow_card = BorrowCard.query.filter_by(user_id=current_user.id).first()
        if not borrow_card:
            flash('借阅证还未办理，请先办理借阅证！', 'danger')
            return redirect(url_for('user_borrow.borrow_info', book_id=book_id))
        
        # 校验借书证是否过期
        now = datetime.now()
        logger.info(f"当前时间：{now}")
        logger.info(f"过期时间：{borrow_card.valid_until}")
        if borrow_card.valid_until < now:
            flash('借阅证超期，请续签借阅证！', 'danger')
            return redirect(url_for('user_borrow.borrow_info', book_id=book_id))
        
        # 校验书籍库存
        if book.available_count <= 0:
            flash('书籍库存不足，请等待书籍归还！', 'danger')
            return redirect(url_for('user_borrow.borrow_info', book_id=book_id))
        
        # 校验是否存在逾期未还的记录
        if BorrowBook.query.filter_by(user_id=current_user.id, 
                                  is_overdue=True, is_return=False).first():
            flash('存在逾期未还的记录，请先还书！', 'danger')
            return redirect(url_for('user_borrow.borrow_info', book_id=book_id))
        
        # 校验用户借阅数量
        if BorrowBook.query.filter_by(user_id=current_user.id, is_return=False).count() >= borrow_card.borrow_limit:
            flash('借阅数量已达上限，请先还书！', 'danger')
            return redirect(url_for('user_borrow.borrow_info', book_id=book_id))
        # 查询当前书籍是否已经借阅
        borrow_book = BorrowBook.query.filter_by(
            book_id=book_id, 
            user_id=current_user.id, 
            is_return=False).first()
        if borrow_book:
            # 如果已经借阅，则更新借阅时间
            borrow_book.return_time = borrow_book.return_time + relativedelta(days=7)
            flash(f'书籍已续借，系统将为您自动设置还书时间为{borrow_book.return_time}', 'success')
        else:
            # 如果没有借阅，则创建一条新的借阅记录
            borrow_book = BorrowBook()
            borrow_book.book_id = book_id
            borrow_book.book_name = book.name
            borrow_book.borrow_time = now
            borrow_book.return_time = now + relativedelta(months=1)
            borrow_book.user_id = current_user.id
            borrow_book.username = current_user.username
            borrow_book.card_id = borrow_card.card_id
            db.session.add(borrow_book)
            # 书籍库存-1
            if book.available_count > 0:
                book.available_count -= 1
            flash(f'书籍已借阅，系统将为您自动设置还书时间为{borrow_book.return_time}', 'warning')

        db.session.commit()
        flash('书籍借阅成功！', 'success')
        return redirect(url_for('user_borrow.borrow_info', book_id=borrow_book.book_id))
    return redirect(url_for('user_borrow.borrow_list'))
